#include "SbotPluginManager.h"

SbotPluginManger::SbotPluginManger() {}

SbotPluginManger::~SbotPluginManger() {}

int SbotPluginManger::InitAllPlugin(QQmlEngine* engine) {
    SbotPlugin* pluginInterface = nullptr;

    for (SbotPluginObject* obj : this->plugins) {
        pluginInterface = qobject_cast<SbotPlugin*>(obj->sbotPluginObj);
        pluginInterface->PluginQmlInit(engine);
    }

    return 0;
}

int SbotPluginManger::RefreshPlugin(const QString& path) {
    QDir pluginsDir(path);
    const QStringList entries = pluginsDir.entryList(QDir::Files);
    int loadedPluginsCount = 0;

    for (const QString& fileName : entries) {
        // 获取插件元对象
        QPluginLoader pluginLoader(pluginsDir.absoluteFilePath(fileName));
        QObject* plugin = pluginLoader.instance();
        QJsonObject metaData = pluginLoader.metaData();

        if (plugin) {
            plugins.append(new SbotPluginObject((SbotPlugin*)plugin, metaData));
            loadedPluginsCount++;
        } else {
            pluginLoader.unload();
        }
    }

    return loadedPluginsCount;
}

QObject* SbotPluginManger::GetPluginUi(int index) {
    SbotPlugin* pluginObj = nullptr;

    if (!this->plugins.count() || index >= this->plugins.count()) {
        return nullptr;
    }

    pluginObj = qobject_cast<SbotPlugin*>(this->plugins[index]->sbotPluginObj);

    return pluginObj->GetQmlObject();
}

int SbotPluginManger::GetPluginNum() { return this->plugins.count(); }

const QString& SbotPluginManger::GetPluginName(int index) {
    SbotPlugin* pluginObj = nullptr;

    pluginObj = qobject_cast<SbotPlugin*>(this->plugins[index]->sbotPluginObj);

    return pluginObj->GetPluginInfo().pluginName;
}

const QIcon& SbotPluginManger::GetPluginLogo(int index) {
    SbotPlugin* pluginObj = nullptr;

    // if (!this->plugins.count() || index >= this->plugins.count()) {
    //     return nullptr;
    // }

    pluginObj = qobject_cast<SbotPlugin*>(this->plugins[index]->sbotPluginObj);

    return pluginObj->GetPluginInfo().pluginLogo;
}

int SbotPluginManger::StartPluginThread(int index) {
    SbotPlugin* pluginObj = nullptr;

    if (!this->plugins.count() || index >= this->plugins.count()) {
        return -1;
    }

    pluginObj = qobject_cast<SbotPlugin*>(this->plugins[index]->sbotPluginObj);

    if (pluginObj->isStopped) {
        pluginObj->PluginThreadStart();
    } else if (pluginObj->isPaused) {
        pluginObj->PluginThreadResume();
    }

    return SBT_NERR;
}

void SbotPluginManger::StopPluginThreadAll() {
    SbotPlugin* pluginInterface = nullptr;

    for (SbotPluginObject* obj : this->plugins) {
        pluginInterface = qobject_cast<SbotPlugin*>(obj->sbotPluginObj);
        pluginInterface->PluginThreadStop();
    }
}
